const crypto = require("crypto");

function get_req_url(params, endpoint) {
    params["Signature"] = escape(params["Signature"]);
    const url_strParam = sort_params(params);
    return "https://" + endpoint + "/?" + url_strParam.slice(1);
}

function formatSignString(reqMethod, endpoint, path, strParam) {
    let strSign = reqMethod + endpoint + path + "?" + strParam.slice(1);
    return strSign;
}
function sha1(secretKey, strsign) {
    let signMethodMap = { HmacSHA1: "sha1" };
    let hmac = crypto.createHmac(signMethodMap["HmacSHA1"], secretKey || "");
    return hmac.update(Buffer.from(strsign, "utf8")).digest("base64");
}

function sort_params(params) {
    let strParam = "";
    let keys = Object.keys(params);
    keys.sort();
    for (let k in keys) {
        //k = k.replace(/_/g, '.');
        strParam += "&" + keys[k] + "=" + params[keys[k]];
    }
    return strParam;
}

/**
 * @description 用于腾讯云api v1加密封装
 * @param {string} endpoint 请求地址
 * @param {Object} config 请求参数 { Url:图片地址, base64:图片base64格式, data:{key:value}}
 * @param {string} action 接口功能名称
 * @param {string} version 版本
 * @param {string} region 地域
 * @return {Object} {sign,params,url} sign 签名 params 参数 url 请求地址
 */
function enciphered({
    endpoint = "ft.tencentcloudapi.com",
    config,
    action,
    region = "ap-shanghai",
    version = "2020-03-04",
}) {
    return new Promise((resolve, reject) => {
        // 密钥参数
        const SECRET_ID = "AKID0znMK2EuTnIYaMq3HFThfQu7Z1GGusnR";
        const SECRET_KEY = "UjyzkF9pLcbMqB7zcy2yh9rVR8YigRv3";
        const Timestamp = Math.round(Date.now() / 1000); // 时间戳 2016-06-06 12:02:48, 此参数作为示例，以实际为准
        const Nonce = Math.round(Math.random() * 65535); // 随机正整数

        let params = {};
        params["Action"] = action;
        params["Nonce"] = Nonce;
        params["Region"] = region;
        params["SecretId"] = SECRET_ID;
        params["Timestamp"] = Timestamp;
        params["Version"] = version;
        params["Url"] = config.Url ? config.Url : "";
        if (config.Url) {
            params["Url"] = config.Url;
        }
        if (!config.Url && config["Image"]) {
            params["Image"] = config["Image"];
        }
        params["RspImgType"] = config.RspImgType ? config.RspImgType : "base64";
        // 参数
        if (config && config.data) {
            let obj = config.data;
            let keys = Object.keys(config.data);
            keys.forEach(key => {
                params[key] = obj[key];
            });
        }

        // 1. 对参数排序,并拼接请求字符串
        let strParam = sort_params(params);

        // 2. 拼接签名原文字符串
        const reqMethod = "GET";
        const path = "/";
        let strSign = formatSignString(reqMethod, endpoint, path, strParam);
        // 3. 生成签名串
        params["Signature"] = sha1(SECRET_KEY, strSign);
        // 4. 进行url编码并拼接请求url
        resolve({
            sign: params.Signature,
            params,
            url: get_req_url(params, endpoint),
        });
    });
}

module.exports = enciphered;
export default enciphered;
